import axios from 'axios'

const getters = {
  getTotalQuantity (state) {
    const res = state.itemList.reduce((sum, item) => sum + item.count, 0)
    return res
  },
  getTotalCost (state) {
    const res = state.itemList.reduce((sum, item) => sum + (item.count * item.price), 0)
    return res
  }
}
const mutations = {
  setItemList (state, newValue) {
    state.itemList = newValue
  },
  setItemCount (state, { id, value }) {
    const goods = state.itemList.find((items) => items.id === id)
    goods.count = value
  }
}
const actions = {
  async getItemList (context) {
    const res = await axios.get('http://localhost:3000/cart/')
    context.commit('setItemList', res.data)
  },
  async updateCount (context, { id, value }) {
    await axios.patch(`http://localhost:3000/cart/${id}`, {
      count: value
    })
    context.commit('setItemCount', {
      id: id,
      value: value
    })
  }
}
export default {
  namespaced: true,
  state () {
    return {
      itemList: []
    }
  },
  getters,
  mutations,
  actions
}
